<script>
    require('com/DrawingManager_min.css');
    require('com/DrawingManager');

    export default {
        created() {

        },
        mounted() {
            this.$on('add-electric-fence', () => {
                this.electronic_fence_name=''
                this.warning_in=0
                this.warning_out=0
                this.clear()
                this.isAdd = true;
                this.title ="添加电子围栏";
                this.show();
            });

            //展示编辑网点
            this.$on('edit-electric-fence', (data) => {
                this.electronic_fence_name=''
                Object.keys(data).forEach(it=>{
                    if(typeof this.$data[it]!=='undefined') this.$data[it]=data[it]
                })

                

                this.isAdd = false;
                this.title ="编辑电子围栏";
                this.show();
            });
    
        },

        components:{
           
        },


        data(){
            return {
                title: '',

                // 是否为添
                isAdd: false,

                isShow: false,
                
               
                id: '',

                //维度 
                lat : '', 

                // 经度
                lng: '',
                

                // 网点地址
                parking_lot_address: '',

                // 网点名字
                electronic_fence_name: '',

            
                // 省份
                province: '',



                // 驶入报警
                warning_in: '',

                // 使出报警
                warning_out: '',

                // 网点坐标
                points:[],

                // 搜索地址
                searchAddrss: '',

                // 绘制管理对象
                $drawingManager: '',

                // 当前选择的多边形绘制按钮
                curChoose: 0,

                // 标记点选中状态
                markerChoose: false,

                // 地图对象
                $map: '',

                //标记点
                $marker: '',

                //多边形
                $polygon: '',


            }
        },
        watch: {
            'isShow': function(value) {
                if (value) {
                    this.$nextTick(()=> {
                        this.init();
                    }); 
                }
            }
        },

        methods: {
            show(){
                this.isShow = true;
            },

            close(){
                //触发隐藏蒙版事件
                this.isShow = false;

            },

            chooseBtn(value) {
                this.curChoose = value;
            },

            addMarkerBtnChoose(){
                this.markerChoose = true;
            },


            init(){
                // 地图
                this.$data.$map = this.map();
                this.drawManager(this.$data.$map);
                //初始化搜索
                this.$data.$localSearch = new BMap.LocalSearch(
                    this.$data.$map, 
                    
                    {
                        renderOptions:{map:  this.$data.$map}
                    }
                );
               
              
                if (!this.isAdd) {
                    //创建坐标点对象
                    var points =  [];
                    
                    this.points.forEach((item) => {
                        points.push(new BMap.Point(item.lng, item.lat));
                    });

                    console.log(points)

                    var point = new BMap.Point(this.lng, this.lat);

                    this.createDefaultMarker(point);
                    this.createDefaultNetArea(points);

                    this.$data.$map.centerAndZoom(point, 11);
                    this.$data.$map.setViewport(points)
                    
                }else {
                    this.$data.$map.centerAndZoom('深圳', 11);
                }
               
            },

            // 坐标点地址解析
            geocoder(pt) {
                var geoc = new BMap.Geocoder();

                geoc.getLocation(pt, (rs) => {
                    var addComp = rs.addressComponents;

/*                    this.parking_lot_address = addComp.street +((addComp.street&&addComp.streetNumber)?", ":"") + addComp.streetNumber;*/
                });
            },
           
            //创建网点中心点
            createDefaultMarker(point) {
                this.$data.$marker  = new BMap.Marker(point);
                // 激活可编辑
                this.$data.$marker.enableDragging();


                this.$data.$marker.addEventListener('dragend', (e) => {
                    this.lat = e.point.lat;
                    this.lng = e.point.lng;

                    // 拖拽后解析地址
                    this.geocoder(e.point);
                });

                this.$data.$map.addOverlay(this.$data.$marker);
            },


            mapSearch(){
                 this.$data.$localSearch.search(this.searchAddrss);
            },

            //创建默认网点区域
            createDefaultNetArea(points) {
                var styleOptions = {
                    strokeColor:"red",    //边线颜色。
                    // fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                    strokeWeight: 3,       //边线的宽度，以像素为单位。
                    strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
                    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
                    strokeStyle: 'solid' //边线的样式，solid或dashed。
                };


                this.$data.$polygon = new BMap.Polygon(
                    points,
                    styleOptions
                );

                this.$data.$map.addOverlay(this.$data.$polygon);
                // 激活可编辑
                // this.$data.$polygon.enableEditing();

                this.$data.$polygon.addEventListener('lineupdate', (e) => {
                    this.poins = this.$data.$polygon.getPath();
                });
            },


            map(){
                var map = new BMap.Map('map');

                //启动自动适应容器变化
                map.enableAutoResize();

                // 初始化地图到指定坐标点
               
                map.enableScrollWheelZoom(true);

                return  map
            },


            //绘制管理
            drawManager(map) {
                var styleOptions = {
                    strokeColor:"red",    //边线颜色。
                    // fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                    strokeWeight: 3,       //边线的宽度，以像素为单位。
                    strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
                    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
                    strokeStyle: 'solid' //边线的样式，solid或dashed。
                };

                this.$data.$drawingManager = new  BMapLib.DrawingManager(
                    map,
                    {
                        isOpen:false, //是否开启绘制模式
                        enableDrawingTool: false, //是否显示工具栏
                        drawingToolOptions: {
                            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                            offset: new BMap.Size(5, 5), //偏离值
                        },
                        circleOptions: styleOptions, //圆的样式
                        polylineOptions: styleOptions, //线的样式
                        polygonOptions: styleOptions, //多边形的样式
                        rectangleOptions: styleOptions //矩形的样式
                    }
                );
            },

            // 清除所有
            clear(){
                // 清空保存数据
                this.points.length = 0;
                this.lat = '';
                this.lng = '';

                // 清除覆盖物
               if(this.$data.$map) this.$data.$map.removeOverlay(this.$data.$marker);
               if(this.$data.$map) this.$data.$map.removeOverlay(this.$data.$polygon);
            },

            //绘制多边形
            draw: function(model) {
                var that = this;

                //如果模式等于marker
                if (model === 'marker') {
                    this.$data.$map.removeOverlay(this.$data.$marker);
                }else {
                    this.$data.$map.removeOverlay(this.$data.$polygon);
                };

                this.$data.$drawingManager.open();
                this.$data.$drawingManager.setDrawingMode(model);
              
                this.$data.$drawingManager.addEventListener('overlaycomplete', function(eName, e) {
                    if (e.drawingMode === 'marker') {
                        // 清除前一个标记点
                        that.$data.$map.removeOverlay(that.$data.$marker);
                        that.$data.$marker = e.overlay;
                        that.$data.$map.addOverlay(that.$data.$marker);

                        var  point = e.overlay.getPosition();

                        that.lat =  point.lat;
                        that.lng  =  point.lng;

                        that.geocoder(point);
                    }else {
                        that.$data.$map.removeOverlay(that.$data.$polygon);

                        that.$data.$polygon = e.overlay;

                        that.$data.$map.addOverlay(that.$data.$polygon);
                       
                        var partsPoint =  that.$data.$polygon.getPath();
                        var points = [];
                        partsPoint.forEach((item) => {
                            points.push({
                                lat: item.lat,
                                lng: item.lng
                            });
                        });

                     
                        that.points = points;
                       
                    };

                    that.$data.$drawingManager.close();
                    // 将按钮选中状态置为空
                    that.curChoose = 0;
                    that.markerChoose = false;



                    
                });
            },

            

            // 保存网点
            save(){
                var url = this.isAdd ? 'electronic_fence/create_electronic_fence': 'electronic_fence/update_electronic_fence';

                if (this.$data.points.length === 0) {
                    this.$message({
                        message:'请绘制围栏',
                        type:'error',
                        duration:10000,
                    })
                    return;
                }
                this.$http.post(
                    url,
                    {
                       id: this.id,
                       electronic_fence_name: this.electronic_fence_name,      

                       lng: this.lng,             
                       lat : this.lat,            
                       points : this.$data.points,
                       enclosure_status: this.enclosure_status, 
                       //0:不提示;1提示 ,全部用-1
                       warning_in: this.warning_in == true ? 1 : 0,
                       //0:不提示;1提示 ,全部用-1
                       warning_out: this.warning_out == true ? 1 : 0, 

                    }
                ).then((response) => {
                    if(!response.result) {
                      this.$message('操作成功')
                      this.$parent.$emit('refresh')
                      this.close()
                    }
                });
            }

        }
    }
</script>


<template>
    <div class="u-mask-layer" v-if='isShow'>

        <div class="add-dot">
            <p class='title'>
                {{title}}
                <i @click='close'>x</i>
           
            </p>
            <div class="content">
                <ul class="operate ">
                    <template>
                        <li>
                            <label>围栏名称：</label>
                            <input type='text' placeholder='请输入围栏名称' class='area' v-model="electronic_fence_name">
                        </li>
                        <li>
                            <label>网点地址：</label>
                            <input type='button' value='手动选取网点' class='btn' :class="{active: markerChoose}" @click="draw('marker'),addMarkerBtnChoose()">
                        </li>
                        <li class='intnet-area'>
                            <label>围栏区域：</label>

                            <div class='choose'>
                                <div class='cycle f-fl' :class="{active: curChoose === 1}"  @click="draw('polyline'),chooseBtn(1)">折线</div>
                                <div class='rectangle f-fl' :class="{active: curChoose === 2}"  @click="draw('rectangle'), chooseBtn(2)"> 矩形</div>
                                <div class='polygon f-fl' :class="{active: curChoose === 3}"  @click="draw('polygon'), chooseBtn(3)"> 多边形</div>
                            </div>
                            <p class='clear' @click="clear"><input type='button' value='清除所选区域'></p>

                        </li>
                    </template>
                    <li>
                        <label>报警类型：</label>
                        <span>
                            <input type="checkbox" name="" v-model="warning_in">
                            驶入报警
                        </span>
                        <span>
                            <input type="checkbox" name="" v-model="warning_out">
                            驶出报警
                        </span>
                       
                    </li>

                     
                </ul>
                <div class="map">
                    <div class="map-area" id="map">

                    </div>
                    <p class='search'>
                        <input type='text' placeholder='请输地点搜索' v-model="searchAddrss" @keyup.enter="mapSearch">
                        <input type='button' value='搜索' class='btn'  @click="mapSearch">
                    </p>
                </div>

            </div>
           
            <div class='bottom'>
                <button class='disapper' @click='close'>取消</button>
                <button class='save' @click='save'>保存</button> 
            </div>
        </div>

    </div>
    
</template>


<style lang="scss"  scoped>

    .u-mask-layer{
        position:fixed;
        width: 100%;
        height: 100%;
        overflow: hidden;
        z-index: 10000;
        left: 0;
        top: 0;
        background: rgba(0, 0, 0, 0.50);
    }
     .add-dot{
        width:1100px;
        height:700px;
        position:fixed;
        top:50%;
        left: 50%;
        transform:translateX(-50%) translateY(-50%);
        z-index: 20;
        background: #FFFFFF;
        border:1px solid #979797;
        border-radius:8px;
         font-size:16px;
        .title{
            position: relative;
            
            width:1100px;
            height:44px;
            text-align: center;
            line-height:44px;

            font-size:12px;
            color: #3D5266;
            border-bottom: 1px solid #DDDDDD;
            i{
                position: absolute;
                top:0;
                right:15px;
                width:13px;
                height:13px;
                color: #BFC0C0;
                cursor: pointer;
            }
        }
        .content{
            position:relative;
            width:1100px;
            display:flex;
            height:700-49*2px;
            .operate{
                position:relative;
                width:160+96px;
                height:700-44*2px;

                li{
                    width:160+96px;
                    margin-top:10px;
                    margin-left:10px;
                    input[type='button']{
                        cursor: pointer;
                    }
                    label{
                        width:90px;
                        line-height:30px;
                        display:block;
                        font-size:12px;
                        color: #888888;;
                        vertical-align: middle;
                    }
                    span{
                        margin-right:20px;
                        font-size:12px;
                        input{
                            vertical-align: middle;
                        }
                    }
                    .area{
                        width:236px;
                        height:30px;
                        text-indent:12px;
                        background: #FFFFFF;
                        border: 1px solid #DDDDDD;
                        border-radius:2px;
                        &.gray{
                             background:#ddd;
                         }
                    }
                    .btn{
                            width:134px;
                            border-radius:2px;
                            text-align: center;
                            line-height:30px;
                            text-indent:0px;
                            font-size:12px;
                            cursor:pointer ;
                            border: 1px solid #3494E7;
                            color:#fff;
                            background: #3494E7;
                            &.active{
                                 border: 1px solid #2976b8;
                                 color:#ccc;
                                 background:#2976b8;
                           
                            }
                    }
                   
                   


                }
                .intnet-area{
                    width:160+96+20px;
                    p{
                        width:160+96+20px;
                        height:34px;
                    }

                    .choose{
                        width:160+96+20px;
                        height:60px;
                        .rectangle,.cycle,.polygon{
                            width:95px;
                            height:30px;
                            margin:5px 20px 5px 0;
                            background: #FFFFFF;
                            border: 1px solid #D2DAE1;
                            border-radius:2px;
                            text-align: center;
                            line-height:30px;
                            text-indent:0px;
                            font-size:12px;
                            color: #888888;
                            cursor: pointer;

                        }
                        .active{

                            border: 1px solid #3494E7;
                            color: #3494E7;
                           
                        }
                        
                    }
                    .clear{
                        width:160+96+20px;
                        height:30px;
                        margin-top:30px;
                        input{
                            width:231px;
                            height:30px;
                            border-bottom: none;
                            background: #FFFFFF;
                            border: 1px solid #E33244;
                            border-radius:2px;

                            font-size:12px;
                            color: #E33244;
                 
                        }

                    }
                }


            }
            .map{
                position: relative;
                width:1100-160-96px;
                height:700-44*2px;
                .map-area{
                    width:100%;
                    height:700-44*2-20px;;
                    background:#DDDDDD;
                    box-sizing: border-box;
                    margin:10px  10px 10px 0;
                }
                    .search{
                        width:160+96+70px;
                        height:30px;
                        position:absolute;
                        top:48px;
                        right:36px;
                    input{
                        width:206px;
                        height:30px;

                        border: 1px solid #DDDDDD;
                        border-radius:2px;
                        text-indent:20px;
                    }
                    .btn{
                        width:80px;
                        height:32px;
                        background: #3494E7;
                        border-radius:2px;
                        font-size:12px;
                        color: #FFFFFF;
                        border: none;
                        margin-left:10px;
                        text-indent:0px;

                    }
                    }
            }

        }
        .bottom{
                width:1100px;
                height:54px;
                display:flex;
                align-items: center;
                border-top: 1px solid #DDDDDD;
                button{
                    width:100px;
                    height:35px;
                    border: 1px solid #BBBBBB;
                    border-radius: 2px;
                    

                }
                .disapper{
                    margin-left:800px;
                    background: #F1F1F1;
                    border: 1px solid #BBBBBB;
                    border-radius: 2px;
                }
                .save{
                    margin-left:30px;
                    background: #3494E7;
                    border-radius: 2px;
                    color: white;
                }
         }

    }
</style>


